//
//  ASHomeBannerView.m
//  AvatarShow
//
//  Created by xunruiIOS on 2021/4/27.
//

#import "ASHomeBannerView.h"
#import "NSTimer+addition.h"
#import "ASCommentModel.h"
#import "ASHomeBannerModel.h"
#import "ASDetailController.h"

static NSString *ASHomeBannerSubCellStr = @"ASHomeBannerSubCell";

@interface ASHomeBannerSubCell : UICollectionViewCell

@property (strong, nonatomic) UIImageView *mainImage;
@property (strong, nonatomic) UIButton *imageDefultView;

@end

@implementation ASHomeBannerSubCell

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self.contentView addSubview:self.imageDefultView];
        [self.contentView addSubview:self.mainImage];

        [self.mainImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
        [self.imageDefultView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
    }
    return self;
}

- (UIImageView *)mainImage{
    if (!_mainImage) {
        _mainImage = [UIImageView new];
        _mainImage.contentMode = UIViewContentModeScaleAspectFill;
        _mainImage.clipsToBounds = YES;
        _mainImage.backgroundColor = [ASTool backgroundRandomColor];
        _mainImage.layer.masksToBounds = YES;
        _mainImage.layer.cornerRadius = 6.f;
    }
    return _mainImage;
}

- (UIButton *)imageDefultView{
    if (!_imageDefultView) {
        _imageDefultView = [UIButton new];
        [_imageDefultView setBackgroundColor:[UIColor colorWithHexString:@"f7f7f7"]];
        _imageDefultView.userInteractionEnabled = NO;
    }
    return _imageDefultView;
}

@end

@implementation ASHomeBannerView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.scrollHeight = [[self class] headScrollHeight];
        [self addSubview:self.collectionView];
        [self addSubview:self.pageCon];
        [self initialTimer];
        [self createScrollData];

        [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(14);
            make.right.mas_equalTo(-14);
            make.top.mas_equalTo(10);
            make.height.mas_equalTo(75);
        }];
    }
    return self;
}

///加载顶部滚动数据
- (void)createScrollData{
//    NSString * temp  = NSTemporaryDirectory();
//    NSString * filePath = [temp stringByAppendingPathComponent:COMMENTLISTKEY];
//    ASCommentModel *oldModel = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
//    if (oldModel) {
//        self.dataSource = oldModel.spaceid186;
//    }
}

///初始化计时器
- (void)initialTimer {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:kTimeInterval target:self selector:@selector(nextPage:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    [self.timer pause];
}

- (void)nextPage:(NSTimer *)timer {
    if (_dataSource.count < 2) return;
    if (self.currentPage >= 5000000) {
        self.currentPage = 0;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.collectionView setContentOffset:CGPointMake(++self.currentPage * (SCREEN_WIDTH - 28), 0) animated:YES];
        self.pageCon.currentPage = self.currentPage%self.dataSource.count;
    });
}

- (void)setDataSource:(NSArray *)dataSource {
    [_timer pause];
    _dataSource = dataSource;
    [self.collectionView reloadData];
    
    if (_dataSource.count < 2) return;
    self.pageCon.numberOfPages = dataSource.count;
    _currentPage = 0;
    [_timer resumeWithTimeInterval:kTimeInterval];
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = CGSizeMake(SCREEN_WIDTH-28, 75);
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.pagingEnabled = YES;
        _collectionView.layer.masksToBounds = YES;
        _collectionView.layer.cornerRadius = 5.f;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor colorWithHexString:@"ffffff"];
        
        // 注册cell
        [_collectionView registerClass:[ASHomeBannerSubCell class] forCellWithReuseIdentifier:ASHomeBannerSubCellStr];
    }
    return _collectionView;
}

- (EllipsePageControl *)pageCon{
    if (!_pageCon) {
        _pageCon = [[EllipsePageControl alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-130)/2, self.height - 16, 130, 20)];
        _pageCon.backgroundColor = [UIColor clearColor];
        _pageCon.otherColor = [UIColor colorWithHexString:@"#ffffff"];
        _pageCon.currentColor = [UIColor colorWithHexString:@"#ffffff"];
        _pageCon.controlSize = 5;
        _pageCon.delegate=self;
    }
    return _pageCon;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _dataSource.count > 1 ?  5000000 : _dataSource.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ASHomeBannerSubCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ASHomeBannerSubCellStr forIndexPath:indexPath];
    if (self.dataSource.count > indexPath.item % _dataSource.count) {
        ASHomeBannerSubModel *model = self.dataSource[indexPath.item % _dataSource.count];
        [cell.mainImage sd_setImageWithURL:[NSURL URLWithString:model.imageurl]];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.dataSource.count > indexPath.row % _dataSource.count) {
//        [ASTool addUMTongJiKey:@"find" subKey:@"Page_hits" titleStr:@"banner点击"];
        ASHomeBannerSubModel *model = self.dataSource[indexPath.row % _dataSource.count];
        [self clickSubWithModel:model];
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    _currentPage = scrollView.contentOffset.x / self.collectionView.width;
    self.pageCon.currentPage = self.currentPage%self.dataSource.count;

//    _pageControl.currentPage = _currentPage % _dataSource.count;
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [_timer pause];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [_timer resumeWithTimeInterval:kTimeInterval];
}

#pragma mark - EllipsePageControlDelegate
-(void)ellipsePageControlClick:(EllipsePageControl *)pageControl index:(NSInteger)clickIndex{
    
}

- (void)clickSubWithModel:(ASHomeBannerSubModel *)model{
    [ASTool addUMTongJiKey:@"home" subKey:@"home_top" titleStr:@"banner"];
    ASDetailController *detailVC = [ASDetailController new];
    detailVC.hidesBottomBarWhenPushed = YES;
    detailVC.subID = model.picture_id;
    [currViewController().navigationController pushViewController:detailVC animated:YES];
}

///添加点击统计
- (void)addTongJiWithID:(NSString *)tid{
//    [IGHomeApi commentClickWithID:tid Completion:^(id  _Nonnull result) {
//    } failure:^(NSError * _Nonnull error) {
//    }];
}

///顶部滚动的高度
+ (CGFloat)headScrollHeight{
    CGFloat mainW = SCREEN_WIDTH - 30;
    CGFloat bili = (float)345 / (float)145;
    CGFloat mainH = mainW / bili;
    return mainH;
}

+ (CGFloat)headHeight{
    CGFloat scrH = [[self class]headScrollHeight];
    return scrH + 15 + 102;
}
@end
